package edu.hrbu.systemadmin.aspect;

import cn.hutool.json.JSONUtil;
import edu.hrbu.systemadmin.annotation.HasPerms;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;

import static edu.hrbu.systemadmin.util.ConstUtil.*;

/**
 * @author 徐登宇
 */
@Aspect
@Component
public class AuthAspect {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Before("@annotation(hasPerms)")
    public void beforeProcess(JoinPoint joinPoint, HasPerms hasPerms){
        String[] needPerms = hasPerms.perms();
        HttpServletRequest request = getRequest();
        String token = request.getHeader(HEADER_AUTHORIZATION);
        String permsKey=PERMS_PREFIX+token;
        String permsArrJson = stringRedisTemplate.opsForValue().get(permsKey);
        List<String> ownPerms = JSONUtil.toList(permsArrJson, String.class);
        boolean f=false;
        for (String e:needPerms){
            if (ownPerms.contains(e)){
                f=true;
                break;
            }
        }
        if (!f){
            throw new RuntimeException("您未有该权限，禁止访问！");
        }
    }
}
